package cn.it.service.impl;

import cn.it.dao.MainDao;
import cn.it.entity.PageResult;
import cn.it.entity.QueryPageBean;
import cn.it.pojo.User;
import cn.it.service.MainService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = MainService.class)
@Transactional
public class MainServiceImpl implements MainService {

    @Autowired
    private MainDao mainDao;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<User> page = mainDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<User> list = page.getResult();
        return new PageResult(total, list);
    }

    @Override
    public void add(User user, Integer[] roleIds) {


        //BCryptPasswordEncoder bc =new BCryptPasswordEncoder();
        String password = user.getPassword();
        String bcryPassword = passwordEncoder.encode(password);
        user.setPassword(bcryPassword);

        mainDao.add(user);

        Integer userId = user.getId();

        for (Integer roleId : roleIds) {
            Map<String, Integer> map = new HashMap<>();
            map.put("user_id", userId);
            map.put("role_id", roleId);
            mainDao.setUserAndUserRole(map);
        }
    }
}
